package net.zhangbaolin.systemadmin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import net.zhangbaolin.systemadmin.common.Jwt;
import net.zhangbaolin.systemadmin.common.RedisUtils;
import net.zhangbaolin.systemadmin.common.ResponseJson;
import net.zhangbaolin.systemadmin.entity.Login;
import net.zhangbaolin.systemadmin.entity.User;
import net.zhangbaolin.systemadmin.service.LoginService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    AuthenticationManager authenticationManager;
    @Resource
    private RedisUtils redisUtils;

    @Value("${diy.user-info-timeout}")
    private Long userInfoTimeOut;

    @Override
    public ResponseJson login(User user) {
        System.out.println("用户名：" + user.getUsername() + "，密码：" + user.getPassword());
        //AuthenticationManager authenticate进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //如果认证没通过，给出对应的提示
        if (Objects.isNull(authenticate)) {
            throw new AccessDeniedException("账户或者密码错误");
        }

        Login login = (Login)  authenticate.getPrincipal();
        String userid = login.getUser().getId().toString();

        String token = null;
        try {
            Jwt jwt = new Jwt();
            token = jwt.createToken(userid);
            System.out.println(token);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        //把完整的用户信息存入redis  userid作为key
        redisUtils.set("userid:" + userid, JSON.toJSONString(login, SerializerFeature.WriteClassName), userInfoTimeOut, TimeUnit.SECONDS);

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);

        return ResponseJson.ok(map);
    }

    @Override
    public ResponseJson logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Login loginUser = (Login) authentication.getPrincipal();
        Long userid = loginUser.getUser().getId();
        redisUtils.remove("userid:"+userid);
        return ResponseJson.ok("退出成功");
    }
}
